$(function() {
	$("#grid-table").jqGrid({
		url:'../user/findUser.do',
		postData:{'name':""},
		mtype: 'POST',
		datatype : "json",
		multiselect: true,
		multiboxonly:true,
		colModel:[
			{name:'id', hidden:true  },
			{name:'deptId', hidden:true  },
			{label:'用户名',name:'username', width:100, editable:false  },
			{label:'用户编码', name:'code', width:100, editable:false },
			{label:'单位', name:'deptName', width:100, editable:false },
		 ],
		 jsonReader: {  
		 	root:"results", page:"pageNum", total:"totalPageNum",          //   很重要 定义了 后台分页参数的名字。
		 	records:"totalCount", id : "id"
		 },
		viewrecords : true,
		rowNum:15,
		pager : "#grid-pager",
		altRows: true,
		loadComplete : function() {
			updatePagerIcons(this);
			enableTooltips(this);
		},
		onPaging: function(pgButton) {      
		},
		onSelectRow: function (rowid, status) {
			editUser();
		},
		autowidth: true
	});
 
	$("#add_grid-table").click(function(){
		addUser();
	});		
	
	initTree();
	validata();
});

function editUser(){
	var grid = $("#grid-table");
	var ids = RM.jqgrid.ids(grid);
	if(ids.length == 0 || ids.length > 1){
		if(ids.length == 0){
			RM.msg("请选择一行数据进行编辑");
		}
		else{
			$('#userinfo').hide();
			return;
		}
	}else{
		clearform('userform');
		$("#userinfo .title").text("人员编辑");
		var rowsData = $('#grid-table').jqGrid('getRowData',ids[0]);
		$('#form_user_id').val(rowsData.id);
	    $('#form_user_name').val(rowsData.username);
	    $('#form_user_code').val(rowsData.code);
	    $('#form_user_dept').val(rowsData.deptId);
	    
	    selectTreeNode(rowsData.deptId);
	    $('#userinfo').show();
	    //用户名不可编辑
	    $('#form_user_name').attr("readonly","readonly");
	}
	
}

function resetPassword(){
	var grid = $("#grid-table");
	var ids = RM.jqgrid.ids(grid);
	if(ids.length == 0){
		RM.alert("请至少选择一行进行删除");
		return false;
	}
	RM.confirm("确认重置所选的"+ids.length+"条记录密码吗?", function (){
		RM.close();
		$.post("../user/resetPassword.do",{"ids":ids},function (data){
			grid.jqGrid().trigger("reloadGrid");
			RM.alert("操作成功");
		},"json");
	}); 
	
}

function deleteUser(){
	RM.jqgrid.dels($("#grid-table"),"../user/dels.do");
	$('#userinfo').hide();
}

function doSaveUser(){
	$("#userform").submit();
}

function addUser(){
	clearform('userform');
	selectTreeNode("0");
	$("#userinfo .title").text("人员添加");
    $('#userinfo').show();
  //用户名可编辑
    $('#form_user_name').removeAttr("readonly");
}


function selectTreeNode(id){
	if(id == "" || id == null){
		id = 0;
	}
	var zTree_Menu = $.fn.zTree.getZTreeObj("treeDemo"); 
	var node = zTree_Menu.getNodeByParam("id",id );  
    zTree_Menu.selectNode(node,true);//指定选中ID的节点  
    zTree_Menu.expandNode(node, true, false);//指定选中ID节点展开
    
    $("#form_user_dept").val(id);
    $("#deptName").val(node.name);
}

 

var setting = {
    view: {
    	selectedMulti: false,
    	dblClickExpand: false
    },
    check: {
        enable: false
    },
    data : {  
        key : {  
            name : "name"  
        },  
        simpleData : {  
            enable : true,  
            idKey : "id",  
            pIdKey : "parentId",  
            rootPId : 0  
        }  
    },   
    edit: {
        enable: false
    },
    callback: {
    	onClick: zTreeOnClick
	}
};

function initTree(){
	$.post("../dept/findAllJson.do",{},function (data){
 		$.fn.zTree.init($("#treeDemo"), setting, data); 
	},"json");
}
function zTreeOnClick(event, treeId, treeNode) {
    if (treeNode) {
         $("#form_user_dept").val(treeNode.id);
         $("#deptName").val(treeNode.name);
    }
    hideMenu();
}
function showMenu() {
	var cityObj = $("#deptName");
	var cityOffset = $("#deptName").offset();
	$("#menuContent").css({left:0, top:"30px",width:$("#menuContent").closest(".input-group").width()}).slideDown("fast");
	$("body").bind("mousedown", onBodyDown);
}
function hideMenu() {
	$("#menuContent").fadeOut("fast");
	$("body").unbind("mousedown", onBodyDown);
}
function onBodyDown(event) {
	if (!(event.target.id == "menuBtn" || event.target.id == "menuContent" || $(event.target).parents("#menuContent").length>0)) {
		hideMenu();
	}
}

var postFlag = false;

function clearform(formid){
	$('#'+formid)[0].reset();
    $("#"+formid+" :input").not(":button, :submit, :reset, .clear_save ").val("").removeAttr("checked").remove("selected"); 
    $("#"+formid+" .error").html("");
}

function sendMyAjax(url,data,callback){
	postFlag = true;
	$.ajax({
		   type: "POST",
		   url:url,
		   data:data, 
		   success: function(msg){
			   if(msg.code != '0'){
				  RM.alert(msg.message);
			   }else{
				 callback(); 
			   }
			   postFlag = false;
		   } ,
		   error: function(error){
			   RM.alert(error);
			   postFlag = false;
		   }
	});
}

function validata(){
	$("#userform").validate({
		submitHandler: function() {
			if($("#form_user_dept").val() == "" || $("#form_user_dept").val() == null){
				RM.alert("请先选择单位");
				return;
			}
			if(!postFlag){
				var callback= function(){
					$("#grid-table").jqGrid().trigger("reloadGrid");  
					$('#userinfo').hide();
				};
				sendMyAjax("../user/save.do",$('#userform').serialize(),callback);
			}
		}
	});
}